package com.hanlin.day04;

/**
 * @Author:hl.yuan
 * @Date:2024/6/27 22:13
 * @Description: 数组实现队列
 **/
public class ArrayQueue {

    /**
     * 记录队列的尾部
     */
    private int end;
    /**
     * 记录队列的头部
     */
    private int begin;
    /**
     * 记录队列的容量
     */
    private int size;
    /**
     * 记录队列的上线
     */
    private final int limit;
    /**
     * 数组
     */
    private int[] array;

    public ArrayQueue(int limit) {
        this.limit = limit;
        array = new int[limit];
        end = 0;
        begin = 0;
        size = 0;
    }

    /**
     * 向队列添加数据
     */
    public void push(int value) {
        if (size >= limit) {
            throw new RuntimeException("队列满了，不能在添加了");
        }
        size++;
        array[end] = value;
        end = nextIndex(end);
    }

    /**
     * 从队列中取出数据
     */
    public int pull() {
        if (size == 0) {
            throw new RuntimeException("队列为空，不能取数据");
        }
        size--;
        int value = array[begin];
        begin = nextIndex(begin);
        return value;
    }

    /**
     * 获取下一个坐标，超过队列长度时，返回0
     *
     * @param index
     * @return
     */
    public int nextIndex(int index) {
        return (index + 1) % limit;
    }

    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(10);
        for (int i = 0; i < 10; i++) {
            arrayQueue.push(i);
        }
        for (int i = 0; i < 10; i++) {
            System.out.println(arrayQueue.pull());
        }
        arrayQueue.push(999);
        arrayQueue.pull();
        System.out.println("测试完毕");
    }

}
